package com.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CASDemo01 {

    public static void main(String[] args) {

        //Integer是包装类，所有包装类之间的对象比较，全部使用equals方法比较，对于Integer var = ?在-128至127之间的赋值，Integer对象是在IntegerCache.cache产生，
        //会复用已有对象，这个区间内的Integer值可以直接使用==进行判断，但是这个区间之外的所有数据，都会在堆上产生，并不会复用已有对象，这是一个大坑，推荐使用equals方法进行判断。
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(23, 1);

        new Thread(()->{
            int stamp = atomicStampedReference.getStamp(); //获得版本号
            System.out.println("a1=>"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Lock lock = new ReentrantLock();

            System.out.println("a:"+atomicStampedReference.compareAndSet(23,2022
                    ,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1));

            System.out.println("a2=>"+atomicStampedReference.getStamp());

        },"a").start();

        new Thread(()->{
            int stamp = atomicStampedReference.getStamp(); //获得版本号
            System.out.println("b1=>"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("b:"+atomicStampedReference.compareAndSet(23,2022
                    ,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1));

            System.out.println("b2=>"+atomicStampedReference.getStamp());

        },"b").start();

    }

}
